function hasClass(obj, cls) {
	return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}

function addClass(obj, cls) {
	if (!this.hasClass(obj, cls)) obj.className += " " + cls;
}

function removeClass(obj, cls) {
	if (hasClass(obj, cls)) {
		var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
		obj.className = obj.className.replace(reg, ' ');
	}
}

mui.init();
var subpages = ['feed.html', 'channel.html', 'collect.html', 'settings.html'];
var subpage_style = {
	top: '0px',
	bottom: '51px',
};
var has_show = {};

var view_ids = ['feed', 'channel', 'collect', 'settings'];
var webviews = [];
var active_id = view_ids[0];
mui.plusReady(function() {
	var self = plus.webview.currentWebview();
	for (var i = 0; i < subpages.length; i++) {
		var t = {};
		//var sub = plus.webview.create(subpages[i], view_ids[i], subpage_style, {});
		var sub = mui.preload({
			url: subpages[i],
			id: view_ids[i],
			styles: subpage_style,
		});
		if (i > 0) {
			sub.hide();
		} else {
			sub.show();
			has_show[view_ids[i]] = 'true';
		}
		self.append(sub);
	}

	mui('.mui-bar-tab').on('tap', 'a', function(e) {
		var target_id = this.getAttribute('data-id');
		if (target_id == active_id) {
			return;
		}

		plus.webview.show(target_id);
		plus.webview.hide(active_id);
		active_id = target_id;
	});

	var now = new Date();
	var storage = window.localStorage;
	if (!storage["clear_cache_at"] || storage["clear_cache_at"] < now.getTime()) {
		for (var i = 0; i < storage.length; i++) {
			var storage_key = storage.key(i);
			if (/^daily_/g.test(storage_key) || /^rec_/g.test(storage_key ||
					/^topic_/g.test(storage_key) || /^frame_/g.test(storage_key))) {
				delete storage[storage_key];
			} else if (/^img_/g.test(storage_key)) {
				plus.io.resolveLocalFileSystemURL(storage_key, function(entry) {
					entry.remove();
				}, function(error) {});
				delete storage[storage_key];
			}
		}
		storage["clear_cache_at"] = now.getTime() + 6* 86400000;
		console.log("缓存清理完毕");
	}
	setTimeout(function(){
		plus.navigator.closeSplashscreen();
	}, 600)

});

var first = null;
mui.back = function() {
	//首次按键，提示‘再按一次退出应用’
	if (!first) {
		first = new Date().getTime();
		mui.toast('再按一次退出应用');
		setTimeout(function() {
			first = null;
		}, 1000);
	} else {
		if (new Date().getTime() - first < 1000) {
			plus.runtime.quit();
		}
	}
};

//console.log(mui('.mui-tab-item[data-id=collect]')[0].innerHTML);

function switch_view(target_id) {
	if (target_id == active_id) {
		return;
	}

	removeClass(mui('.mui-tab-item[data-id=' + active_id + ']')[0], 'mui-active');
	addClass(mui('.mui-tab-item[data-id=' + target_id + ']')[0], 'mui-active');
	plus.webview.show(target_id);
	plus.webview.hide(active_id);
	active_id = target_id;
}